關於 React 小書:PropTypes 和 Component 參數驗證


Posted by YongChenSu on 2020-12-09

isRequired

已設定參數驗證但傳入非指定參數會提供較為友善的錯誤訊息

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

class Comment extends Component {
  static propTypes = {
    comment: PropTypes.object.isRequired
  }

  render () {
    const { comment } = this.props
    return (
      <div className='comment'>
        <div className='comment-user'>
          <span>{comment.username} </span>:
        </div>
        <p>{comment.content}</p>
      </div>
    )
  }
}

ReactDOM.render(
  <Comment comment={1} />,
  document.getElementById('root')
)



PropTypes 和 Component 參數驗證

PropTypes.array
PropTypes.bool
PropTypes.func
PropTypes.number
PropTypes.object
PropTypes.string
PropTypes.node
PropTypes.element


PropTypes 參數驗證的優點

  1. 因錯誤訊息會提供更詳細的資訊,幫助 debug,雖然撰寫上會稍微麻煩一點點,但非常推薦使用 PropTypes 驗證參數。
  2. 在 Component 的開發、使用規範更明確。

參考資源


#程式導師實驗計畫第四期 #前端 #React #react 小書 #propTypes







Related Posts

[Day 03] - Vault 的基本操作

[Day 03] - Vault 的基本操作

[day 04] Class & constructor: 吃語法糖別噎到

[day 04] Class & constructor: 吃語法糖別噎到

JavaScript 五四三 Ep.07 Array.prototype.indexOf()

JavaScript 五四三 Ep.07 Array.prototype.indexOf()


Comments